package com.dhecp.project.purchase.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.purchase.domain.Distribution;
import com.dhecp.project.purchase.domain.DistributionSon;
import com.dhecp.project.purchase.domain.PurchasePlan;
import com.dhecp.project.purchase.mapper.DistributionMapper;
import com.dhecp.project.purchase.mapper.DistributionSonMapper;
import com.dhecp.project.purchase.service.DistributionService;
import com.dhecp.project.storage.domain.AssemblyPlan;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: kjecp
 * @description: 1688铺货 服务实现层
 * @author: hlf
 * @create: 2022-08-27 09:38
 */
@Service
public class DistributionServiceImpl extends BaseModuleServiceImpl implements DistributionService {


    @Autowired
    private DistributionMapper purchaseMapper;
    @Autowired
    private DistributionSonMapper sonMapper;
    @Autowired
    private UpdateLogService updateLogService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.hr.domain.Distribution
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public Distribution queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return purchaseMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.hr.domain.Distribution>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<Distribution> queryListByGoodsID(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return purchaseMapper.selectByGoodsID(params);
    }

    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.Distribution
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public Distribution findByGuid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return purchaseMapper.findById(params);
    }

	@Override
	public Distribution findByPcodeAndSkuid(String pcode, String skuid) {
		return purchaseMapper.findByPcodeAndSkuid(pcode, skuid);
	}


    /**
     * @Description: 根据Guid 查询子件数据
     * @Param: [pGuid]
     * @return: java.util.List<com.dhecp.project.purchase.domain.DistributionSon>
     * @Author: hlf
     * @date: 2022-08-22 13:48
     */
    @Override
    public List<DistributionSon> querySonList(String goodsID) throws Exception {
        return sonMapper.querySonList(goodsID);
    }

    /**
     * @Description: 根据Guid 查询子件数据
     * @Param: [pGuid]
     * @return: java.util.List<com.dhecp.project.purchase.domain.DistributionSon>
     * @Author: hlf
     * @date: 2022-08-22 13:48
     */
    @Override
    public List<DistributionSon> querySonList2(String pGuid) throws Exception {
        return sonMapper.querySonList2(pGuid);
    }

    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.hr.domain.Distribution>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<Distribution> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPage();
        return purchaseMapper.select(params);
    }

    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.hr.domain.Distribution>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<Distribution> queryList2(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPage();
        return purchaseMapper.select2(params);
    }

    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.hr.domain.Distribution>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<Distribution> queryGroupList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPage();
        return purchaseMapper.queryGroupList(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        Distribution oldData = new Distribution();
        Distribution distribution = JSON.parseObject(params.get("infoItems").toString(), Distribution.class);

        if (distribution.getGuid() != null && !distribution.getGuid().equals("")) {
            Map<String, Object> params2 = new HashMap<String, Object>();
            params2.put("guid",distribution.getGuid());
            oldData = purchaseMapper.findById(params2);
            distribution.setUpdateTime(new Date());
            distribution.setUpdateUser(ShiroUtils.getUserId());
            purchaseMapper.update(distribution);
            updateLogService.addUpdateLog(params.get("moduleTable").toString(), distribution.getGuid(), oldData, distribution, "修改");
        } else {
            distribution.setGuid(RandomValueUtils.getGUID());
            distribution.setCreateTime(new Date());
            distribution.setCreateUser(ShiroUtils.getUserId());
            purchaseMapper.insert(distribution);
            updateLogService.addInsertLog(params.get("moduleTable").toString(), distribution.getGuid(), "新增");
        }


        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), distribution.getGoodsID());
    }

    /**
     * @Description: 保存子表数据
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveDataSon(Map<String, Object> params) {

        Distribution onDate = JSON.parseObject(params.get("infoItem").toString(), Distribution.class);

        params.put("guid",onDate.getGuid());
        Distribution onDate1 = purchaseMapper.findById(params);

        List<DistributionSon> oldData = sonMapper.querySonList2(onDate.getGuid());
        for (DistributionSon item : oldData
        ) {
            sonMapper.delete(item);
        }

        String[] sCode = onDate.getsCode().split(",");
        for (String i : sCode
        ) {
            DistributionSon data = new DistributionSon();//每个商品智能铺货一次，第二次需要删除原先的铺货
            data = sonMapper.findById(i);
            if (data != null) {
                sonMapper.delete(data);
            }

            DistributionSon distributionSon = new DistributionSon();
            distributionSon.setGuid(RandomValueUtils.getGUID());
            distributionSon.setpGuid(onDate1.getGuid());
            distributionSon.setPid(onDate1.getId());
            distributionSon.setCreateTime(new Date());
            distributionSon.setCreateUser(ShiroUtils.getUserId());
            distributionSon.setsCode(i);
            distributionSon.setsKUID(onDate1.getsKUID());
            distributionSon.setGoodsID(onDate1.getGoodsID());
            sonMapper.insert(distributionSon);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<Distribution> businessDataList = JSON.parseArray(params.get("infoItems").toString(), Distribution.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (Distribution businessData : businessDataList) {
            purchaseMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }


    /**
     * @Description: 查询总数
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-31 9:32
     */
    @Override
    public Integer queryCount(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return purchaseMapper.queryCount(params);
    }


}